<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\OpenShop\InvestmentPromotion\ShopManualEnum;
use App\Library\FeiShu\SendFs;
use App\Models\OpenShop\InvestmentPromotion\OpenShopShopManual;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Service\OpenShop\Pdf\PdfMakerService;
use Exception;
use Illuminate\Support\Facades\Log;
use Kuafu\File\FileUtil;

class ShopManualService extends BaseService
{
    public string $orderNo;

    public ?OpenShopSignOrderModel $signOrder;

    public function __construct(string $orderNo)
    {
        $this->orderNo   = $orderNo;
        $this->signOrder = OpenShopSignOrderModel::query()
                                                 ->with(['baseInfoRel', 'contractRel'])
                                                 ->where('orderNo', $orderNo)
                                                 ->first();
    }

    public static function getAllByOrderNo(string $orderNo): array
    {
        $list    = [];
        $manuals = OpenShopShopManual::query()
                                     ->where('orderNo', $orderNo)
//            ->orderBy('type', 'asc')
                                     ->orderBy('weight', 'asc')
                                     ->orderBy('id', 'desc')
                                     ->get();
        foreach ($manuals as $manual) {
            if (!isset($list[$manual->shopCode])) {
                $list[$manual->shopCode] = [
                    'shopCode'      => $manual->shopCode,
                    'hasDisclosure' => false,
                    'files'         => [],
                ];
            }
            $item = $manual->only(['id', 'name', 'url', 'type']);
            if (ShopManualEnum::TYPE_DISCLOSURE == $manual->type) {
                $list[$manual->shopCode]['hasDisclosure'] = true;
            }
            $item['url'] = FileUtil::domain() . '/' . $manual->url;
            if ($manual->type == ShopManualEnum::TYPE_DISCLOSURE) {
                $item['url'] = privateFilePath($manual->url);
            }
            $list[$manual->shopCode]['files'][] = $item;
        }
        return array_values($list);
    }

    /**
     * 给某个[订单+某个门店]制作(更新)全部手册
     * @param $orderNo
     * @param $shopCode
     * @return void
     * @throws Exception
     */
    public function make($shopCode)
    {
        try {
            if (!$this->signOrder) {
                return;
            }

            if (null === $this->signOrder->baseInfoRel || null === $this->signOrder->contractRel) {
                return;
            }

            $identityCardModel = OpenShopUserIdentityCardModel::getDataByOrderNo($this->orderNo);
            if (null === $identityCardModel) {
                return;
            }
            $name = $identityCardModel->name;

            /* 循环统一处理 */
            $typeFileList = ShopManualEnum::getTypeFileList();

            foreach ($typeFileList as $typeKey => $item) {
                $manualModel = OpenShopShopManual::firstOrNew([
                    'orderNo'  => $this->orderNo,
                    'type'     => $typeKey,
                    'shopCode' => $shopCode,
                ]);

                if ($manualModel->version != $item['version']) {
                    $manualModel->version = $item['version'];
                    $tmpFile              = forward_static_call($item['func'], "{$name}{$shopCode} 机密信息 严禁外传");
                    $arr                  = FileUtil::uploadFile($tmpFile);
                    $manualModel->url     = $arr['path'] ?? '';
                    $manualModel->name    = sprintf('No.%s-%s(%s)', $shopCode, $item['name'], $item['version']);
                    $manualModel->weight  = $item['weight'];
                    $manualModel->save();
                    @unlink($tmpFile);
                }
            }

            // 授权书生成
            $this->genQualificationImage($shopCode);
        } catch (\Exception $exception) {
            Log::error('报错了', ['exception' => $exception]);
            SendFs::newRobot()->setTitleContent('OSS 上传文件异常', $exception->getMessage())->send();
        }

    }

    /**
     * 生成授权书
     *
     * @param string $shopCode
     * @param string $address
     * @param string $version
     */
    public function genQualificationImage(string $shopCode, string $address = '', string $version = '20220601')
    {
        /**
         * 公司资质证明
         */
        $manualModel = OpenShopShopManual::firstOrNew([
            'orderNo'  => $this->signOrder->orderNo,
            'type'     => ShopManualEnum::TYPE_CERTIFICATE,
            'weight'   => 5,
            'shopCode' => $shopCode,
            'version'  => $version
        ]);

        if (empty($manualModel->id)) {
            OpenShopShopManual::query()
                              ->where('orderNo', $this->signOrder->orderNo)
                              ->where('type', ShopManualEnum::TYPE_CERTIFICATE)
                              ->where('shopCode', $shopCode)
                              ->update(['isDeleted' => 1]);
        }

        $manualModel->name = sprintf('No.%s-%s(%s)', $shopCode,
            QualificationImageService::CERTIFICATE_OF_AUTHORIZATION_NAME, $version);

        $signOrder = OpenShopSignOrderModel::query()
                                           ->with(['baseInfoRel', 'contractRel'])
                                           ->where('orderNo', $this->signOrder->orderNo)
                                           ->first();

        $identityCardModel = OpenShopUserIdentityCardModel::getDataByOrderNo($this->signOrder->orderNo);

        if (null === $identityCardModel) {
            return;
        }
        $name = $identityCardModel->name;

        $address = empty($address) ? $signOrder->baseInfoRel->chooseShopAddressPrefix : $address;


        if ($signOrder->contractRel->contractors == 1) {
            $manualModel->url = QualificationImageService::shareImage($shopCode, $name,
                    $identityCardModel->identityCardNumber, $address,
                    $signOrder->contractRel->startTime, $signOrder->contractRel->endTime)['path'] ?? '';
        } else {
            $manualModel->url = QualificationImageService::shareCompanyImage($shopCode,
                    $signOrder->contractRel->companyName,
                    $signOrder->contractRel->businessLicenseNumber, $address,
                    $signOrder->contractRel->startTime, $signOrder->contractRel->endTime)['path'] ?? '';
        }
        $manualModel->save();
    }

}
